package org.gangcai.mac.shop.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.just.agentweb.AgentWeb;
import com.orhanobut.dialogplus.DialogPlus;

import org.gangcai.mac.shop.R;
import org.gangcai.mac.shop.api.AppAPI;
import org.gangcai.mac.shop.bean.CommonResonseBean;
import org.gangcai.mac.shop.bean.GoodDescBean;
import org.gangcai.mac.shop.bean.GoodInfoBean;
import org.gangcai.mac.shop.bean.GoodInfoBean.GoodInfoDetails;
import org.gangcai.mac.shop.bean.GoodInfoBean.GoodInfoDetails.PicturesBean;
import org.gangcai.mac.shop.bean.GoodInfoBean.GoodInfoDetails.PropertiesBean;
import org.gangcai.mac.shop.common.MultiStatusActivity;
import org.gangcai.mac.shop.holders.LocalImageHolderView;
import org.gangcai.mac.shop.manager.RetrofitManagers;
import org.gangcai.mac.shop.oberver.CommonObserver;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.android.schedulers.AndroidSchedulers;

import static org.gangcai.mac.shop.constants.Constant.CODE_SUCC;

public class SPShopDetailActivity extends MultiStatusActivity {

    @BindView(R.id.convenientBanner)
    ConvenientBanner convenientBanner;
    @BindView(R.id.shopTitle)
    TextView shopTitle;
    @BindView(R.id.container)
    LinearLayout container;
    @BindView(R.id.btn)
    Button btn;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.sfhsj)
    TextView sfhsj;
    @BindView(R.id.scrollView)
    NestedScrollView scrollView;
    @BindView(R.id.webView)
    WebView webView;
    private String id;
    private GoodInfoDetails goodInfo;
    private AgentWeb mAgentWeb;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        ButterKnife.bind( this );
        id = getIntent().getExtras().getString( "goodsID" );
        initTitleBarView( titlebar, "商品详情" );
//        addWebView(content);
        loadData();
    }

    private void loadData() {
        multipleStatusView.showLoading();
        String uidString = SPUtils.getInstance().getString( "uid", "0" );
        RetrofitManagers.create().goods_infos( "goods", id, uidString )
                .compose( this.<GoodInfoBean>bindToLifecycle() )
                .observeOn( AndroidSchedulers.mainThread() )
                .subscribe( new CommonObserver<GoodInfoBean>( multipleStatusView ) {
                    @Override
                    public void onSuccess(GoodInfoBean value) {

                        if (value.getCode() == CODE_SUCC) {
                            goodInfo = value.getInfo();
                            List<PicturesBean> pictures = goodInfo.getPictures();

                            if (pictures != null && pictures.size() > 0) {
                                ArrayList<String> viewpageDatas = new ArrayList<>();
                                for (int i = 0; i < pictures.size(); i++) {
                                    viewpageDatas.add( pictures.get( i ).getThumb() );
                                }
                                setViewPagerData( viewpageDatas );
                            }

                            shopTitle.setText( goodInfo.getGoods_name() );
                            money.setText( "¥" + goodInfo.getShop_price() );
                            List<PropertiesBean> properties = goodInfo.getProperties();
                            if (properties != null && properties.size() > 0) {
                                String propertieString="商品参数";
                                for (int i = 0; i < properties.size(); i++) {
                                    propertieString+=("\n"+properties.get( i ).getName()+":"+properties.get( i ).getValue());
                                }
                                sfhsj.setText( propertieString );
                            }

                            loadDescData();
                        }
                    }
                } );
    }

    private void loadDescData() {
        RetrofitManagers.create().goods_info_desc( "goods", id, "desc" )
                .compose( this.<GoodDescBean>bindToLifecycle() )
                .observeOn( AndroidSchedulers.mainThread() )
                .subscribe( new CommonObserver<GoodDescBean>( multipleStatusView ) {
                    @Override
                    public void onSuccess(GoodDescBean value) {

                        if (value.getCode() == CODE_SUCC) {

                            String goods_brief = value.getInfo().getGoods_brief();
//                            String goods_desc = value.getInfo().getGoods_desc();
//                            if (goods_desc != null && goods_desc.length() > 8) {
//                                goods_brief+=goods_desc;
//                            }
                            addWebView(goods_brief);
                        }
                    }
                } );
    }

    private void addWebView(String content) {
        webView.setWebViewClient( new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                view.loadUrl( url );
                return true;
            }


            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                return super.shouldInterceptRequest( view, url );
            }

        } );
        webView.loadData( content, "text/html; charset=UTF-8", null );
//        webView.loadUrl( content );
        webView.setHorizontalFadingEdgeEnabled( false );
        webView.setVerticalFadingEdgeEnabled( false );
        webView.setHorizontalScrollBarEnabled( false );
        //声明WebSettings子类
        WebSettings webSettings = webView.getSettings();

//如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled( true );

//支持插件
//        webSettings.setPluginsEnabled(true);

//设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort( true ); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode( true ); // 缩放至屏幕的大小

//缩放操作
        webSettings.setSupportZoom( false ); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls( false ); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls( false ); //隐藏原生的缩放控件

//其他细节操作
        webSettings.setCacheMode( WebSettings.LOAD_CACHE_ELSE_NETWORK ); //关闭webview中缓存
        webSettings.setAllowFileAccess( true ); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically( true ); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically( true ); //支持自动加载图片
        webSettings.setDefaultTextEncodingName( "utf-8" );//设置编码格式
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
     /*   mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(container, new LinearLayout.LayoutParams(-1, -1))
                .useDefaultIndicator()
                .createAgentWeb()
                .ready()
                .go("http://www.jd.com");

        final WebView wv = mAgentWeb.getWebCreator().getWebView();*/
      /*  wv.setOnTouchListener(new View.OnTouchListener() {

            private float startx;
            private float starty;
            private float offsetx;
            private float offsety;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        v.getParent().requestDisallowInterceptTouchEvent(true);
                        startx = event.getX();
                        starty = event.getY();
                        break;
                    case MotionEvent.ACTION_MOVE:

                        boolean scrollDown = scrollView.canScrollVertically(1);
                        boolean scrollUp = wv.canScrollVertically(-1);
                        if (!scrollDown) {
                            v.getParent().requestDisallowInterceptTouchEvent(true);
                        }

                        if (!scrollUp) {
                            v.getParent().requestDisallowInterceptTouchEvent(false);
                        }

                        break;
                    default:
                        break;
                }
                return false;
            }
        });*/

     /*   wv.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        wv.setVerticalScrollBarEnabled(false);
        wv.setVerticalScrollbarOverlay(false);
        wv.setHorizontalScrollBarEnabled(false);
        wv.setHorizontalScrollbarOverlay(false);*/

    }

    private void setViewPagerData(List<String> data) {
        convenientBanner.setPages(
                new CBViewHolderCreator<LocalImageHolderView>() {
                    @Override
                    public LocalImageHolderView createHolder() {
                        return new LocalImageHolderView();
                    }
                }, data )
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator( new int[]{R.mipmap.indicator_normal, R.mipmap.indicator_focus} )
                //设置指示器的方向
                .setPageIndicatorAlign( ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL );
        convenientBanner.startTurning( 5000 );
        convenientBanner.setScrollDuration( 3000 );
        try {
            Class<?> clazz = Class.forName( "com.bigkoo.convenientbanner.ConvenientBanner" );
            Field loPageTurningPoint = clazz.getDeclaredField( "loPageTurningPoint" );
            loPageTurningPoint.setAccessible( true );
            ViewGroup o = (ViewGroup) loPageTurningPoint.get( convenientBanner );
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) o.getLayoutParams();
            layoutParams.bottomMargin = SizeUtils.dp2px( 36 );
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getContentView() {
        return R.layout.activity_shop_detail;
    }

    @OnClick(R.id.btn)
    public void onViewClicked() {
        String uidString=SPUtils.getInstance().getString("uid", "");
        if(uidString.length()>0){
            if (goodInfo != null) {
                createCarts(goodInfo.getId());
            }
        }else{
            Intent loginIntent = new Intent( SPShopDetailActivity.this, LoginActivity.class );
            startActivity( loginIntent );
        }

    }

    @Override
    protected void onDestroy() {
        if (webView != null) {
            webView.loadDataWithBaseURL( null, "", "text/html", "utf-8", null );
            webView.clearHistory();

            ((ViewGroup) webView.getParent()).removeView( webView );
            webView.destroy();
            webView = null;
        }
        super.onDestroy();
    }

    private void createCarts(String goods_id) {
        RetrofitManagers.getInstance().create(AppAPI.class).carts_create("carts/create", SPUtils.getInstance().getString("uid"),goods_id,"1")
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new CommonObserver<CommonResonseBean>(prompDialog) {
                    @Override
                    public void onSuccess(CommonResonseBean value) {
                        if (value.getCode() == 101) {
                            showCartsDialog();
                        }else{
                            Toast.makeText(SPShopDetailActivity.this, "系统繁忙，请稍后再试...", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void showCartsDialog() {
        final DialogPlus dialog = DialogPlus.newDialog( this )
                .setGravity( Gravity.CENTER )
                .setContentBackgroundResource( android.R.color.transparent )
                .setContentWidth( ViewGroup.LayoutParams.WRAP_CONTENT )  // or any custom width ie: 300
                .setContentHeight( ViewGroup.LayoutParams.WRAP_CONTENT )
                .setContentHolder( new com.orhanobut.dialogplus.ViewHolder( R.layout.cartscreate_dialog_layout ) )
                .setExpanded( false )  // This will enable the expand feature, (similar to android L share dialog)
                .create();
        View holderView = dialog.getHolderView();
        holderView.findViewById( R.id.mcart_confirm_btn1 ).setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        } );
        holderView.findViewById( R.id.mcart_confirm_btn2 ).setOnClickListener( new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String uidString=SPUtils.getInstance().getString("uid", "");
                Intent webIntent = new Intent( SPShopDetailActivity.this, WebActivity.class );
                webIntent.putExtra("webString", "http://www.han80.com/mobile/flows.php?user_id="+uidString);
                startActivityForResult( webIntent,1 );
                dialog.dismiss();
            }
        } );

        dialog.show();


    }
}
